<script setup>
import api from '../api/user_api.js'
import { ref, onMounted } from "vue";
import { ElMessageBox, ElMessage, ElForm } from "element-plus";
import lodash from 'lodash'
import roleAPI from '../api/role_api.js'


// 表格数据与分页
const tableData = ref([])
const total = ref(0);

// 对话框状态
const editWinVisible = ref(false);
const addWinVisible = ref(false);

// 查询参数
const searchObj = ref({
  current: 1,
  limit: 10,
  role_id: '',  // 角色ID查询条件
  name: '',
  phone: '',
  email: '',
  gender: ''
});

// 表单数据与验证规则
const obj = ref({});
const roles = ref([]);  // 角色列表数据
const addFormRef = ref(null);
const editFormRef = ref(null);

// 新增表单验证规则
const formRules = ref({
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 16, message: '用户名长度需在1-16位之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度需在6-20位之间', trigger: 'blur' }
  ],
  phone: [
    { required: false, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
});

// 编辑页验证规则（已移除密码相关规则）
const editRules = ref({
  ...formRules.value
});
delete editRules.value.password;  // 确保编辑规则中没有密码验证

// 头像上传处理
const handleUploadSuccess = (response) => {
  obj.value.uimg = response.data;
};

// 数据加载
const search = async () => {
  try {
    const result = await api.page(searchObj.value);
    tableData.value = result.data;
    total.value = result.count;
  } catch (err) {
    ElMessage.error('数据加载失败');
  }
};

onMounted(async () => {
  // 加载角色列表，用于下拉框选项
  roles.value = await roleAPI.all();
  search();
});

// 分页与查询
const handleSizeChange = () => search();
const handleCurrentChange = () => search();
const handlerSearch = () => {
  searchObj.value.current = 1;
  search();
};

// 新增操作
const handleAdd = async () => {
  obj.value = { role_id: 2 };
  roles.value = await roleAPI.all();
  addWinVisible.value = true;
};

const addCommit = async () => {
  if (!addFormRef.value) return;
  addFormRef.value.validate(async (valid) => {
    if (!valid) return;
    try {
      await api.add(obj.value);
      ElMessage.success('新增成功');
      addWinVisible.value = false;
      search();
      obj.value = {};
    } catch (err) {
      ElMessage.error(err.message || '新增失败');
    }
  });
};

// 编辑操作
const handleEdit = async (_, row) => {
  obj.value = lodash.clone(row);
  // 清除可能存在的密码字段
  delete obj.value.password;
  roles.value = await roleAPI.all();
  editWinVisible.value = true;
};

const editCommit = async () => {
  if (!editFormRef.value) return;
  editFormRef.value.validate(async (valid) => {
    if (!valid) return;
    try {
      await api.edit(obj.value);
      ElMessage.success('编辑成功');
      editWinVisible.value = false;
      search();
    } catch (err) {
      ElMessage.error(err.message || '编辑失败');
    }
  });
};

// 删除操作
const handleDelete = (_, row) => {
  ElMessageBox.confirm(
      '确认删除该行数据吗？',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  ).then(async () => {
    try {
      await api.del(row.id);
      ElMessage.success('删除成功');
      search();
    } catch (err) {
      ElMessage.error('删除失败');
    }
  }).catch(() => {});
};

// 取消操作
const editCancel = () => {
  obj.value = {};
  editWinVisible.value = false;
};
const addCancel = () => {
  obj.value = {};
  addWinVisible.value = false;
};
</script>

<template>
  <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top:10px ">
    <el-form-item label="用户名">
      <el-input v-model="searchObj.name" placeholder="请输入用户名" clearable />
    </el-form-item>
    <el-form-item label="手机号">
      <el-input v-model="searchObj.phone" placeholder="请输入手机号" clearable />
    </el-form-item>
    <el-form-item label="性别">
      <el-input v-model="searchObj.gender" placeholder="请输入性别" clearable />
    </el-form-item>
    <el-form-item label="邮箱">
      <el-input v-model="searchObj.email" placeholder="请输入邮箱" clearable />
    </el-form-item>
    <!-- 新增角色下拉框查询条件 -->
    <el-form-item label="角色">
      <el-select v-model="searchObj.role_id" placeholder="请选择角色" clearable style="width: 180px">
        <el-option v-for="item in roles" :key="item.id" :label="item.role_name" :value="item.id" />
      </el-select>
    </el-form-item>
  </el-form>

  <el-form :inline="true">
    <el-form-item>
      <el-button type="primary" @click="handlerSearch">查询</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleAdd">新增</el-button>
    </el-form-item>
  </el-form>

  <el-table :data="tableData" style="width: 100%">
    <el-table-column label="id" width="80">
      <template #default="scope">
        <el-tag>{{ scope.row.id }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="用户名" width="100">
      <template #default="scope">
        <el-tag>{{ scope.row.name }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="头像" width="80">
      <template #default="scope">
        <el-avatar :src="scope.row.uimg" size="medium">
          <img src="@/assets/upload.png" alt="默认头像" v-if="!scope.row.uimg" />
        </el-avatar>
      </template>
    </el-table-column>
    <el-table-column label="角色" width="80">
      <template #default="scope">
        <el-tag>
          {{ roles.find(role => role.id === scope.row.role_id)?.role_name || scope.row.role_id }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column label="性别" width="80">
      <template #default="scope">
        <el-tag>{{ scope.row.gender || '-' }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="电话" width="120">
      <template #default="scope">
        <el-tag>{{ scope.row.phone || '-' }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="邮箱" width="180">
      <template #default="scope">
        <el-tag>{{ scope.row.email || '-' }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="注册时间" width="300">
      <template #default="scope">
        <span>{{ scope.row.time }}</span>
      </template>
    </el-table-column>
    <el-table-column label="处理按钮">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
      v-model:current-page="searchObj.current"
      v-model:page-size="searchObj.limit"
      :page-sizes="[10, 20, 30, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />

  <!-- 编辑对话框 -->
  <el-dialog v-model="editWinVisible" title="编辑" width="500">
    <el-form
        ref="editFormRef"
        :model="obj"
        :rules="editRules"
        label-width="100px"
    >
      <el-form-item label="用户名" prop="name">
        <el-input v-model="obj.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="头像">
        <el-upload
            class="avatar-uploader"
            action="/api/upload/file"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
        >
          <img :src="obj.uimg ? obj.uimg : '/src/assets/upload.png'"
               style="width: 100px; height: 100px; border-radius: 50%;"
               alt="用户头像"/>
        </el-upload>
      </el-form-item>
      <el-form-item label="角色" prop="role_id">
        <el-select v-model="obj.role_id" placeholder="请选择" style="width: 240px">
          <el-option v-for="item in roles" :key="item.id" :label="item.role_name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="性别">
        <el-input v-model="obj.gender" autocomplete="off" />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model="obj.phone" autocomplete="off" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="obj.email" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editCancel">取消</el-button>
      <el-button type="primary" @click="editCommit">提交</el-button>
    </template>
  </el-dialog>

  <!-- 新增对话框 -->
  <el-dialog v-model="addWinVisible" title="新增" width="500">
    <el-form
        ref="addFormRef"
        :model="obj"
        :rules="formRules"
        label-width="100px"
    >
      <el-form-item label="用户名" prop="name">
        <el-input v-model="obj.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="obj.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="头像">
        <el-upload
            class="avatar-uploader"
            action="/api/upload/file"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
        >
          <img :src="obj.uimg?obj.uimg:'/src/assets/upload.png'"
               style="width: 100px; height: 100px; border-radius: 50%;"
               alt="用户头像"/>
        </el-upload>
      </el-form-item>
      <el-form-item label="角色" prop="role_id">
        <el-select v-model="obj.role_id" placeholder="请选择" style="width: 240px">
          <el-option v-for="item in roles" :key="item.id" :label="item.role_name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="性别">
        <el-input v-model="obj.gender" autocomplete="off" />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model="obj.phone" autocomplete="off" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="obj.email" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="addCancel">取消</el-button>
      <el-button type="primary" @click="addCommit">提交</el-button>
    </template>
  </el-dialog>
</template>

<style></style>
